<template>
  <div class="search-results-container">
    <!-- 顶部导航栏 -->
    <!-- 根据用户类型显示不同的导航栏 -->
    <AdminHeaderNav v-if="isAdmin" />
    <HeaderNav v-else />
    
    <!-- 顶部搜索栏 -->
    <div class="search-header">
      <div class="search-bar">
        <div class="search-box">
          <select v-model="searchType" class="search-select">
            <option value="商品">商品</option>
            <option value="店铺">店铺</option>
          </select>
          <input 
            v-model="searchKeyword" 
            class="search-input" 
            placeholder="搜索商品/品牌/类别"
            @keyup.enter="handleSearch"
          />
          <button class="search-btn" @click="handleSearch">搜索</button>
        </div>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div class="results-content">
      <div class="results-header">
        <h2>搜索结果: "{{ searchKeyword }}"</h2>
        <p v-if="totalResults > 0">共找到 {{ totalResults }} 个商品</p>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>

      <!-- 搜索结果列表 -->
      <div v-else-if="searchResults.length > 0" class="results-grid">
        <ProductCard
          v-for="(item, index) in searchResults"
          :key="index"
          :id="item.id"
          :image="item.image"
          :name="item.name"
          :price="item.price"
          :sold="item.sold"
        />
      </div>

      <!-- 无结果状态 -->
      <div v-else class="no-results">
        <p>没有找到相关商品</p>
        <p>试试其他关键词或调整搜索条件</p>
      </div>

      <!-- 分页控制 -->
      <Pagination
        v-if="searchResults.length > 0 && totalPages > 1"
        :current-page="currentPage"
        :total-pages="totalPages"
        :has-next="hasNext"
        :has-prev="hasPrev"
        @next-page="fetchNextPage"
        @prev-page="fetchPrevPage"
        @first-page="performSearch"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import HeaderNav from '../../components/layout/HeaderNav.vue'
import AdminHeaderNav from '../../components/layout/AdminHeaderNav.vue'
import ProductCard from '../../components/guessYouLike/ProductCard.vue'
import Pagination from '../../components/guessYouLike/Pagination.vue'
import { searchProductsService, type Product } from '../../api/product'
import { useUserStore } from '../../stores/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 根据用户类型决定显示哪个导航栏（role===3 为管理员）
const isAdmin = computed(() => userStore.isAdmin)

// 搜索相关状态
const searchKeyword = ref('')
const searchType = ref('商品')
const searchResults = ref<Product[]>([])
const loading = ref(false)
const currentPage = ref(1)
const totalResults = ref(0)

// 游标分页相关状态
const nextPageAfter = ref<string[]>([])
const prevPageAfter = ref<string[]>([])
const hasNext = ref(false)
const hasPrev = ref(false)

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(totalResults.value / 48)
})

// 从路由参数获取搜索关键词
const initSearch = () => {
  const keyword = route.query.keyword as string
  if (keyword) {
    searchKeyword.value = keyword
    performSearch()
  }
}

// 执行搜索（首次搜索或重新搜索）
const performSearch = async () => {
  if (!searchKeyword.value.trim()) return
  
  try {
    loading.value = true
    console.log('开始执行搜索，关键词:', searchKeyword.value)
    
    // 首次搜索，searchAfter为空
    const response = await searchProductsService(
      searchKeyword.value, 
      '', // searchAfter 首次为空
      'next' // direction next为下一页，prev为上一页
    )
    
    if (response.data && response.data.items) {
      // console.log('搜索结果数据:', response.data)
      // console.log('下一页游标：', response.data.nextPageAfter)
      // console.log('上一页游标：', response.data.prevPageAfter)
      // console.log('是否有下一页：', response.data.hasNext)
      // console.log('是否有上一页：', response.data.hasPrev) 
      // console.log('总商品数量：', response.data.totalHits)
      
      searchResults.value = response.data.items
      totalResults.value = response.data.totalHits || response.data.items.length
      
      // 更新游标信息
      nextPageAfter.value = response.data.nextPageAfter || []
      prevPageAfter.value = response.data.prevPageAfter || []
      hasNext.value = response.data.hasNext || false
      hasPrev.value = response.data.hasPrev || false
      
      // 重置页码
      currentPage.value = 1
    } else {
      searchResults.value = []
      totalResults.value = 0
      nextPageAfter.value = []
      prevPageAfter.value = []
      hasNext.value = false
      hasPrev.value = false
    }
  } catch (error) {
    console.error('搜索失败:', error)
    searchResults.value = []
    totalResults.value = 0
    nextPageAfter.value = []
    prevPageAfter.value = []
    hasNext.value = false
    hasPrev.value = false
  } finally {
    loading.value = false
  }
}

// 获取下一页数据
const fetchNextPage = async () => {
  if (!hasNext.value || !nextPageAfter.value.length) {
    console.log('没有下一页数据')
    return
  }
  
  try {
    loading.value = true
    console.log('准备获取下一页，使用游标:', nextPageAfter.value)
    
    const response = await searchProductsService(
      searchKeyword.value,
      nextPageAfter.value.join(','), // 将数组转换为字符串
      'next'
    )
    
    if (response.data && response.data.items) {
      console.log('下一页搜索结果:', response.data)
      searchResults.value = response.data.items
      
      // 更新游标信息
      nextPageAfter.value = response.data.nextPageAfter || []
      prevPageAfter.value = response.data.prevPageAfter || []
      hasNext.value = response.data.hasNext || false
      hasPrev.value = response.data.hasPrev || false
      
      // 增加页码
      currentPage.value++
      
      console.log('当前页码:', currentPage.value)
      console.log('下一页游标:', nextPageAfter.value)
      console.log('是否有下一页:', hasNext.value)
      console.log('上一页游标:', prevPageAfter.value)
      console.log('是否有上一页:', hasPrev.value)
    }
  } catch (error) {
    console.error('获取下一页失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取上一页数据
const fetchPrevPage = async () => {
  if (!hasPrev.value || !prevPageAfter.value.length) {
    console.log('没有上一页数据')
    return
  }
  
  try {
    loading.value = true
    console.log('准备获取上一页，使用游标:', prevPageAfter.value)
    
    const response = await searchProductsService(
      searchKeyword.value,
      prevPageAfter.value.join(','), // 将数组转换为字符串
      'prev'
    )
    
    if (response.data && response.data.items) {
      console.log('上一页搜索结果:', response.data)
      searchResults.value = response.data.items
      
      // 更新游标信息
      nextPageAfter.value = response.data.nextPageAfter || []
      prevPageAfter.value = response.data.prevPageAfter || []
      hasNext.value = response.data.hasNext || false
      hasPrev.value = response.data.hasPrev || false
      
      // 减少页码
      currentPage.value--
      
      console.log('当前页码:', currentPage.value)
      console.log('下一页游标:', nextPageAfter.value)
      console.log('是否有下一页:', hasNext.value)
      console.log('上一页游标:', prevPageAfter.value)
      console.log('是否有上一页:', hasPrev.value)
    }
  } catch (error) {
    console.error('获取上一页失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    // 更新路由参数
    router.push({
      name: 'SearchResults',
      query: { keyword: searchKeyword.value }
    })
    performSearch()
  }
}

// 组件挂载时初始化
onMounted(() => {
  initSearch()
})

// 监听路由关键词变化，保持页面与地址栏同步
watch(
  () => route.query.keyword,
  (newKeyword) => {
    const keywordStr = (newKeyword as string) || ''
    if (keywordStr && keywordStr !== searchKeyword.value) {
      searchKeyword.value = keywordStr
      performSearch()
    }
  }
)
</script>

<style scoped lang="scss">
.search-results-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 0 2.5rem; /* 与主页保持一致的左右留白 */
}

.search-header {
  background: #fff;
  padding: 1rem 0;
  border-bottom: 1px solid #e0e0e0;
  margin-top: -1.3125rem; /* 与主页保持一致的顶部间距 */
  
  .search-bar {
    max-width: 75rem;
    margin: 0 auto;
    padding: 0 1rem;
    
    .search-box {
      display: flex;
      align-items: center;
      border: 2px solid #ee5530;
      border-radius: 1.25rem;
      background: #fff;
      padding: 0 0.5rem;
      height: 2.5rem;
      max-width: 31.25rem;
      margin: 0 auto;
      
      .search-select {
        border: none;
        background: transparent;
        font-size: 0.875rem;
        color: #333;
        margin-right: 0.5rem;
        outline: none;
      }
      
      .search-input {
        flex: 1;
        border: none;
        font-size: 0.875rem;
        padding: 0 0.5rem;
        outline: none;
        background: transparent;
      }
      
      .search-btn {
        background: #ee5530;
        color: #fff;
        border: none;
        border-radius: 1.125rem;
        font-size: 0.875rem;
        padding: 0 1rem;
        height: 1.75rem;
        cursor: pointer;
        font-weight: bold;
        transition: background 0.2s;
        
        &:hover {
          background: #d94825;
        }
      }
    }
  }
}

.results-content {
  max-width: 75rem;
  margin: 0 auto;
  padding: 1rem 0; /* 移除左右padding，因为外层容器已经有了 */
}

.results-header {
  background: #fff;
  padding: 1rem;
  border-radius: 0.5rem;
  margin-bottom: 1rem;
  
  h2 {
    margin: 0 0 0.5rem 0;
    color: #333;
    font-size: 1.25rem;
  }
  
  p {
    margin: 0;
    color: #666;
    font-size: 0.875rem;
  }
}

.loading-container {
  background: #fff;
  padding: 1rem;
  border-radius: 0.5rem;
}

.results-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 0.75rem;
  margin-bottom: 1.5rem;
}

.no-results {
  background: #fff;
  padding: 3rem;
  border-radius: 0.5rem;
  text-align: center;
  
  p {
    margin: 0.5rem 0;
    color: #666;
    font-size: 0.875rem;
    
    &:first-child {
      font-size: 1rem;
      color: #333;
      font-weight: 500;
    }
  }
}
</style>
